package cn.ybz21.hibot.main;

import cn.ybz21.hibot.util.StaticTopics;
import cn.ybz21.hibot.util.StaticValues;

import com.ibm.micro.client.mqttv3.MqttClient;
import com.ibm.micro.client.mqttv3.MqttConnectOptions;
import com.ibm.micro.client.mqttv3.MqttException;
import com.ibm.micro.client.mqttv3.MqttMessage;
import com.ibm.micro.client.mqttv3.MqttTopic;

/**
 * MQTTV3的订阅消息类
 * 
 * @author ybz
 * @email bingzheng_yan@163.com
 * @time 2016年11月14日
 */
public class MQTTHelper {
	public static MqttClient client;

	public static String subscribeTopic() {
		try {
			// 创建MqttClient
			client = new MqttClient(StaticValues.MQTT_SERVER, "client-"
					+ StaticValues.ID_CLIENT);
			// 回调处理类
			ReceiverCallBack callback = new ReceiverCallBack();
			client.setCallback(callback);
			// 创建连接可选项信息
			MqttConnectOptions conOptions = new MqttConnectOptions();
			conOptions.setCleanSession(false);
			// 连接broker
			client.connect(conOptions);
			// 发布相关的订阅
			for (int i = 0; i < StaticTopics.topics.length; i++) {
				client.subscribe(StaticTopics.topics[i], 1);
			}
			// client.disconnect();
		} catch (Exception e) {
			System.out.println("Connect failed!");
			e.printStackTrace();
			return "failed";
		}
		System.out.println("Connect success!");
		return "success";
	}
	public static void publishMsg(String strTopic, String strMsg) {
		MqttTopic topic = client.getTopic(strTopic);
		MqttMessage message = new MqttMessage(strMsg.getBytes());
		message.setQos(1);
		try {
			topic.publish(message);
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}
}
